//
//  TTLuoShiViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/23.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDiamondViewController.h"
#import <WebKit/WebKit.h>
#import "LLUpDownArrowView.h"
#import "TTDiamondModel.h"
#import "TTDiamondViewCell.h"
#import "YBImageBrowser.h"
#import "TTShopCartView.h"
#import "TTCommondDataModel.h"
#import "TTShopCartViewController.h"
#import "TTDiamondDetailViewController.h"
#import "TTCouponModel.h"

static NSString *cellIdentifier = @"search_diamond_cell";

@interface TTDiamondViewController ()<UITableViewDelegate, UITableViewDataSource, TTDiamondViewCellDelegate>

@property (nonatomic, strong) UILabel *topLabel;
@property (nonatomic, strong) UIButton *infoBtn;
@property (nonatomic, strong) UIView *sortBGView;
@property (nonatomic, strong) LLUpDownArrowView *priceArrowView;    // 按价格
@property (nonatomic, strong) LLUpDownArrowView *weightArrowView;   // 按重量
@property (nonatomic, strong) LLUpDownArrowView *discountArrowView;   // 按折扣
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;   // 页数
@property (nonatomic, strong) NSNumber *sortNum;    // 排序的num
@property (nonatomic, strong) TTShopCartView *shopCartView;
///上次选中的那个
@property (nonatomic, strong) NSIndexPath *lastIndexPath;

///选中的那个model裸石
@property (nonatomic, strong) TTDiamondModel *selectModel;
@property (nonatomic, copy) dispatch_block_t confirmReplaceBlock;
@property (nonatomic, copy) NSString *orderNum;

@end

@implementation TTDiamondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.isExchangeLuoshi ? @"可替换的裸石" : @"搜索结果";
    
    self.page = 0;
    
    [self setupSubview];
    
    if (!self.isExchangeLuoshi) {
        // 购物车物品数量
        @weakify(self)
        _shopCartView = [[TTShopCartView alloc] initWithFrame:CGRectMake(0, 5, 44, 34) imageName:@"shopcart" title:@"" clickShopCartBlock:^(TTShopCartView *cartView) {
            @strongify(self)
            TTShopCartViewController *shopCartVC = [[TTShopCartViewController alloc] init];
            [self.navigationController pushViewController:shopCartVC animated:YES];
        }];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_shopCartView];
    }
   
//    [LLLoadingViewManager showLoadingViewInView:self.tableView];
    
}

- (void)replaceLuoshiOrderNumber:(NSString *)orderNum confirmReplaceBlock:(dispatch_block_t)confirmReplaceBlock
{
    self.orderNum = orderNum;
    self.confirmReplaceBlock = confirmReplaceBlock;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDiamondModel *model = self.dataArray[indexPath.row];
    TTDiamondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    [cell setModel:model clarityCharacteristicsDic:[TTCommondDataModel getClarityCharacteristics] toTimeDic:[TTCommondDataModel toShenZhenTime] findShapeImageDic:[TTCommondDataModel findShapeImageName] cellType:CllTypeWithShowView showDiscount:YES isExchangeLuoshi:self.isExchangeLuoshi];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDiamondModel *model = self.dataArray[indexPath.row];
    
    TTDiamondDetailViewController *detailVC = [[TTDiamondDetailViewController alloc] initWithDiamondModel:model diamondID:nil];
    @weakify(self)
    detailVC.dismissBlock = ^{
        @strongify(self)
        self.shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
        [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:detailVC animated:YES];
    
    model.isSeen = YES;
    [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
    // 保存看过的裸石列表
    NSMutableDictionary *dic = [[USER_DEFAULT objectForKey:seenLuoshiKey] mutableCopy];
    NSMutableArray *barCodeArray = [[USER_DEFAULT objectForKey:lastSeenLuoshiKey] mutableCopy];
    if (barCodeArray == nil) {
        barCodeArray = [NSMutableArray array];
    }
    if (dic == nil) {
        dic = [NSMutableDictionary dictionary];
    } else if (dic.allKeys.count >= 20) {
        [dic removeObjectForKey:barCodeArray.lastObject];
        [barCodeArray removeLastObject];
    }
    [dic setObject:@(YES) forKey:model.GoodsBarCode];
    [barCodeArray addObject:model.GoodsBarCode];
    [USER_DEFAULT setObject:barCodeArray forKey:lastSeenLuoshiKey];
    [USER_DEFAULT setObject:dic forKey:seenLuoshiKey];
    [USER_DEFAULT synchronize];
    
}

// 查看证书
- (void)clickVerifyBtnWithDiamondViewCell:(TTDiamondViewCell *)cell certificateUrlString:(NSString *)urlString
{
    [TTLoginSingle lookCertificateWithUrlString:urlString];
}

///更换裸石选中某个cell
- (void)clickSelectCellWithDiamondViewCell:(TTDiamondViewCell *)cell button:(UIButton *)button model:(TTDiamondModel *)model
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    model.selectExchange = YES;
    if (self.lastIndexPath) {
        TTDiamondModel *lastModel = self.dataArray[self.lastIndexPath.row];
        lastModel.selectExchange = NO;
    }
    
    self.lastIndexPath = indexPath;
    
    self.selectModel = model;
    
    [self.tableView reloadData];
    
}

// 点击购物车
- (void)clickShopCartWithDiamondViewCell:(TTDiamondViewCell *)cell button:(UIButton *)button model:(TTDiamondModel *)model
{
    
    if (!button.selected) {
        [self addShopToCartWithModel:model button:button];
    } else {
        [self deleteShopFromCartWithModel:model button:button];
    }
    
}

// 添加进购物车
- (void)addShopToCartWithModel:(TTDiamondModel *)model button:(UIButton *)button
{
    NSString *title = [NSString stringWithFormat:@"%@ %@ %@ %@ %@ %@ %@ %@", model.Shape, model.DiaSize, model.Color, model.Clarity, model.Cut, model.Sym, model.Polish, model.Flour];
    CGFloat diaSize = model.DiaSize.floatValue * 100;
    int insertSize = [TTLoginSingle findDiamondSizeWithSize:diaSize];
    NSDictionary *mDic = @{
                          @"GoodsType": @(1),
                          @"GoodsTitle": title,
                          @"GoodsImage": model.Shape,
                          @"GoodsBarCode": model.GoodId,
                          @"DiaRef": model.DiaRef,
                          @"SupplierNo": model.SupplierNo,
                          @"CertNo": model.CertNo,
                          @"AddPrice": model.Price,
                          @"InsertSize": @(insertSize),
                          @"DiaSize" : model.DiaSize,
                          @"Number": @(1),
                          @"BuyNumberMax": @(1)
                          };
    NSDictionary *dic = @{
                          @"GoodsList" : @[mDic]
                          };
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:addShopCart_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD showSuccess:@"已加入购物车"];
        
        button.selected = YES;
        model.isInCart = YES;
        
        [TTCommonNetData handleShopCartCodeInfoWithArray:responseObject];
        
        self.shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
        
        // 购物车刷新
        [[TTLoginSingle sharedSingle].shopCartSubject sendNext:@(1)];
        
        NSLog(@"添加成功");
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        NSLog(@"添加失败");
        button.selected = NO;
        model.isInCart = NO;
        
    } showLoadingInView:self.view];
    
}

// 从购物车删除
- (void)deleteShopFromCartWithModel:(TTDiamondModel *)model  button:(UIButton *)button
{
    NSDictionary *dic = @{
                          @"DiaRef" : model.DiaRef,
                          @"CertNo" : model.CertNo,
                          @"SupplierNo" : model.SupplierNo
                          };
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:deleteShopcart_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        button.selected = NO;
        model.isInCart = NO;

        // 购物车刷新
        [[TTLoginSingle sharedSingle].shopCartSubject sendNext:@(1)];
        [TTCommonNetData handleShopCartCodeInfoWithArray:responseObject[@"StockBarCodeList"]];
        
        self.shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;

        NSLog(@"--> 删除成功");
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        NSLog(@"--> 删除失败");
        button.selected = YES;
        model.isInCart = YES;
        
    } showLoadingInView:self.view];
}

// 购物车中的商品条码
- (COPromise *)getShopCartCodeData
{
    COPromise *promise = [COPromise promise];
    
    if ([TTLoginSingle sharedSingle].cartCodeArray.count > 0) {
        
        self.shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
        
        [promise fulfill:[TTLoginSingle sharedSingle].cartCodeArray];
        
        return promise;
    }
    
    @weakify(self)
    [TTCommonNetData getShopCartCodeInfoSuccess:^(NSArray * _Nonnull cartCodeArray, int shopCount) {
        @strongify(self)
        
        self.shopCartView.count = shopCount;
        
        [promise fulfill:cartCodeArray];
        
    } failure:^{
        
        [promise fulfill:@[]];
    }];
    
    return promise;
}


// 裸石列表数据
- (COPromise *)getLuoshiListDataWithCouponMoney:(NSString *)couponMoney
{
    COPromise *promise = [COPromise promise];
    
    [self.paramsDic setObject:@(self.page) forKey:@"pagenum"];
    [self.paramsDic setObject:@(40) forKey:@"pagesize"];
    // 降序
    [self.paramsDic setObject:self.sortNum forKey:@"param.orderFlag"];
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:diamondDataSearchWholesaler_api parameters:self.paramsDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        self.topLabel.text = [NSString stringWithFormat:@"%@粒   汇率：%@", responseObject[@"count"], responseObject[@"dollarRate"]];
        [self.topLabel sizeToFit];
        self.topLabel.height = 30;
        self.infoBtn.frame = CGRectMake(self.topLabel.right + 5, 0, 200, 30);
        
        [TTLoginSingle sharedSingle].dollarRate = [responseObject[@"dollarRate"] floatValue];
        
        if (self.page == 0) {
            [self.dataArray removeAllObjects];
        }
        for (NSDictionary *dic in responseObject[@"data"]) {
            TTDiamondModel *model = [TTDiamondModel modelWithJSON:dic];
            model.cert_supplierNo = [NSString stringWithFormat:@"%@_%@", model.CertNo, model.SupplierNo];
            if (couponMoney) {
                model.couponMoney = [NSString stringWithFormat:@"下单可使用%@元优惠券", couponMoney];
            }
            NSMutableDictionary *dic = [[USER_DEFAULT objectForKey:seenLuoshiKey] mutableCopy];
            model.isSeen = [dic[model.GoodsBarCode] boolValue];
            [self.dataArray addObject:model];
        }
        
        [promise fulfill:self.dataArray];
        
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:@[]];
        
    } showLoadingInView:nil];
    
    return promise;
}

// 获取优惠金额
- (COPromise *)getCouponMoney
{
    COPromise *promise = [COPromise promise];
    
    NSDictionary *dic = @{
        @"CategoryName" : @[@"裸石"],
        @"CouponState" : @0,
        @"PageIndex" : @1,
        @"PageSize" : @1,
    };
    
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:getCouponList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *array = responseObject;
        TTCouponModel *model = [TTCouponModel modelWithJSON:array.firstObject];
        [promise fulfill:model.CouponMoney];
        
            
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:nil];
        
    } showLoadingInView:nil];
    
    return promise;
    
}


- (void)getNetworkDataWithLoadView:(UIView *)loadView
{
//    if (loadView) {
//        [MBProgressHUD showLoadingAnimationOnView:loadView];
//    }
    co_launch(^{
        
//        [LLLoadingViewManager hiddenLoadingViewInView:self.tableView];
        
        NSString *couponMoney = await([self getCouponMoney]);
        NSArray *cartCodeArray = await([self getShopCartCodeData]);
        
        await([self getLuoshiListDataWithCouponMoney:couponMoney]);
        
        // 查找在购物车中的裸石数据
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cert_supplierNo in %@.StockBarCode", cartCodeArray];
        NSArray *inCartArray = [self.dataArray filteredArrayUsingPredicate:predicate];
        for (TTDiamondModel *model in inCartArray) {
            model.isInCart = YES;
        }
        
//        if (loadView) {
//            [MBProgressHUD dismissAnimationOnView:loadView];
//        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        self.tableView.emptyImageName = @"nodata";
        self.tableView.emptyTitel = @"暂无数据";
        [self.tableView reloadEmptyDataSet];
        
        [self.tableView reloadData];
        
    });
    
    
}

///确认更换裸石
- (void)confirmExchangeClick
{
    NSString *goodsImage = [NSString stringWithFormat:@"http://taotuo.oss-cn-hangzhou.aliyuncs.com/TaoTuoApp/Diamonds/icon/%@.png", self.selectModel.Shape];
    NSDictionary *timeDic = [TTCommondDataModel toShenZhenTime];
    NSDictionary *clarityDic = [TTCommondDataModel getClarityCharacteristics];
    NSString *value = @"";
    if (self.selectModel.ClarityCharacteristics.length > 1) {
        NSArray *characteristicsArray = [self.selectModel.ClarityCharacteristics componentsSeparatedByString:@","];
        for (NSString *str in characteristicsArray) {
            NSString *key = [str removeFirstAndLastBlank];
            value = [NSString stringWithFormat:@"%@%@ ", value, clarityDic[key]];
        }
    }
    
    NSDictionary *dic = @{
        @"param.wholesalerName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"param.orderNo" : self.orderNum,
        @"param.goodsBarCode" : self.selectModel.GoodsBarCode,
        @"param.goodsImage" : goodsImage,
        @"param.goodsPrice" : self.selectModel.Price,
        @"param.goodsMadeCircle" : timeDic[self.selectModel.Location],
        @"param.clarityCharacteristics" : value,
    };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:replaceDiamonds_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        if (self.confirmReplaceBlock) {
            self.confirmReplaceBlock();
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
}


- (void)setupSubview
{
    _topLabel = [UILabel labelWithTitle:@"…粒    汇率：…" color:kMainColor fontSize:12];
    _topLabel.frame = CGRectMake(10, 0, 100, 30);
    [self.view addSubview:_topLabel];
    
    UIButton *btn = [UIButton createButtonWithTitle:@"重新搜索" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:12] backgroundColor:nil target:self action:@selector(backAction)];
    btn.frame = CGRectMake(self.view.width - 100, 0, 90, 30);
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.view addSubview:btn];
    
    btn.hidden = self.isExchangeLuoshi;
    
    UIButton *infoBtn = [UIButton createButtonWithTitle:@"目前仅支持替换同级别的裸石！" titleColor:UIColorHex(FFA2A2) titleFont:[UIFont systemFontOfSize:10] backgroundColor:nil target:nil action:nil];
    [infoBtn setImage:[UIImage imageNamed:@"hintgantanhao"] forState:UIControlStateNormal];
    infoBtn.frame = CGRectMake(_topLabel.right + 5, 0, 100, 30);
    infoBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.view addSubview:infoBtn];
    infoBtn.hidden = !self.isExchangeLuoshi;
    _infoBtn = infoBtn;
    
    _sortBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 30, self.view.width, 40)];
    _sortBGView.backgroundColor = UIColorHex(F0F4F7);
    [self.view addSubview:_sortBGView];
    
    CGFloat w = self.view.width / 3.0;
    @weakify(self)
    _priceArrowView = [LLUpDownArrowView arrowViewWithFrame:CGRectMake(0, 0, 0, 40) title:@"按人民币/粒" selectTypeBlock:^(LLUpDownArrowView * _Nullable arrowView, NSString * _Nullable title, ArrowType arrowType) {
        @strongify(self)
        [self.weightArrowView resetView];
        [self.discountArrowView resetView];
        self.sortNum = arrowType == ArrowTypeWithDown ? @(2) : @(1);
        
        self.page = 0;
        [self getNetworkDataWithLoadView:self.tableView.superview];
        
    }];
    _priceArrowView.left = (w - _priceArrowView.width) * 0.5;
    [_priceArrowView setSelected:YES arrowType:ArrowTypeWithUp];
    [_sortBGView addSubview:_priceArrowView];
    
    _weightArrowView = [LLUpDownArrowView arrowViewWithFrame:CGRectMake(0, 0, 0, 40) title:@"按重量" selectTypeBlock:^(LLUpDownArrowView * _Nullable arrowView, NSString * _Nullable title, ArrowType arrowType) {
        @strongify(self)
        [self.discountArrowView resetView];
        [self.priceArrowView resetView];
        self.sortNum = arrowType == ArrowTypeWithDown ? @(6) : @(5);
        
        self.page = 0;
        [self getNetworkDataWithLoadView:self.tableView.superview];
    }];
    _weightArrowView.left = w + (w - _weightArrowView.width) * 0.5;
    [_sortBGView addSubview:_weightArrowView];
    
    _discountArrowView = [LLUpDownArrowView arrowViewWithFrame:CGRectMake(0, 0, 0, 40) title:@"按折扣" selectTypeBlock:^(LLUpDownArrowView * _Nullable arrowView, NSString * _Nullable title, ArrowType arrowType) {
        @strongify(self)
        [self.priceArrowView resetView];
        [self.weightArrowView resetView];
        self.sortNum = arrowType == ArrowTypeWithDown ? @(4) : @(3);
        
        self.page = 0;
        [self getNetworkDataWithLoadView:self.tableView.superview];
    }];
    _discountArrowView.left = 2 * w + (w - _weightArrowView.width) * 0.5;
    [_sortBGView addSubview:_discountArrowView];
    
    // 添加三条线
    [LLLineUtilies addLineInView:_sortBGView startPoint:CGPointMake(w, 8) endPoint:CGPointMake(w, _sortBGView.height - 8) lineColor:UIColorHex(333333)];
    [LLLineUtilies addLineInView:_sortBGView startPoint:CGPointMake(2 * w, 8) endPoint:CGPointMake(2 * w, _sortBGView.height - 8) lineColor:UIColorHex(333333)];

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self getFirstPageData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    
    if (self.isExchangeLuoshi) {
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.sortBGView.bottom);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuide).mas_offset(-45);
        }];
        
        UIButton *bottomBtn = [UIButton createButtonWithTitle:@"确认更换" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(confirmExchangeClick)];
        [self.view addSubview:bottomBtn];
        [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottomLayoutGuide);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(45);
        }];
    }
    
}

- (void)getFirstPageData
{
    self.page = 0;
    [self getNetworkDataWithLoadView:nil];
}

- (void)loadMoreData
{
    self.page++;
    [self getNetworkDataWithLoadView:nil];
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 140;
        _tableView.emptyImageName = @"tao_nodata";
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
//        _tableView.separatorColor = kSeparatorColor;
        _tableView.backgroundColor = COLOR(245, 245, 245, 1);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTDiamondViewCell class]) bundle:nil] forCellReuseIdentifier:cellIdentifier];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.sortBGView.bottom);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}




@end
